package com.example.demo.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@RestController
@RequestMapping("/api/files")
@Tag(name = "文件上传", description = "文件上传相关接口")
public class FileController {

    private final String uploadDir = "uploads/";

    @Operation(summary = "上传文件")
    @PostMapping("/upload")
    @ApiResponse(responseCode = "200", description = "文件上传成功", content = @Content(mediaType = "multipart/form-data"))
    public ResponseEntity<String> uploadFile(@Parameter(description = "要上传的文件") @RequestParam("file") MultipartFile file) {
        System.out.println(file.getName());
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("请选择要上传的文件。");
        }
        try {
            // 创建上传目录如果它不存在
            File directory = new File(uploadDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 获取文件的原始名称和扩展名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 生成新的文件名
            String newFileName = UUID.randomUUID().toString() + fileExtension;

            // 构建文件保存的完整路径
            Path filePath = Paths.get(uploadDir, newFileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 返回可以访问的 URL
            String fileUrl = "/uploads/" + newFileName;
            System.out.println("文件上传成功，路径为：" + filePath.toString()); // 添加日志输出
            return ResponseEntity.status(HttpStatus.OK).body(fileUrl);
        } catch (IOException e) {
            System.out.println("文件上传失败：" + e.getMessage()); // 添加日志输出
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败：" + e.getMessage());
        }
    }

    @Operation(summary = "删除文件")
    @DeleteMapping("/delete")
    @ApiResponse(responseCode = "200", description = "文件删除成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<String> deleteFile(@Parameter(description = "要删除的文件路径") @RequestParam("filePath") String filePath) {
        try {
            // 确保路径在指定的目录范围内
            if (!filePath.startsWith(uploadDir)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("无效的文件路径");
            }


            if (filePath.startsWith("/")) {
                filePath = filePath.substring(1);
            }

            // 构建文件路径
            Path path = Paths.get(filePath);

            System.out.println("要删除的文件路径：" + path.toString());
            if (Files.exists(path)) {
                Files.delete(path);
                return ResponseEntity.status(HttpStatus.OK).body("文件删除成功：" + filePath);
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("文件不存在：" + filePath);
            }
        } catch (IOException e) {
            System.out.println("文件删除失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件删除失败：" + e.getMessage());
        }
    }
}